package org.jadelyre.lyre;

import org.jadelyre.core.NodeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ConnectionCompletionHandler implements CompletionHandler<Void, LyreChannel> {
    private static final Logger logger = LoggerFactory.getLogger(ConnectionCompletionHandler.class);

    @Override
    public void completed(Void result, LyreChannel lyreChannel) {
        LyreClient lyreClient = (LyreClient) lyreChannel.getJadeLyre();
        lyreClient.setStarted(true);
        lyreClient.getCountDownLatch().countDown();
        AsynchronousSocketChannel asynchronousSocketChannel = lyreChannel.getAsynchronousSocketChannel();
        asynchronousSocketChannel.read(lyreChannel.getReadCompletionHandler().getReadByteBuffer(), lyreChannel, lyreChannel.getReadCompletionHandler());
    }

    @Override
    public void failed(Throwable exc, LyreChannel lyreChannel) {
//        System.out.println("ConnectionCompletionHandler:" + exc.toString());
        if (logger.isErrorEnabled()) {
            NodeAddress remoteNodeAddress = lyreChannel.getRemoteNodeAddress();
            logger.error("连接server：{}失败，退出", remoteNodeAddress.getIp() + ":" + remoteNodeAddress.getPort());
        }
        lyreChannel.close();
        System.exit(1);
    }
}
